<?php
/*
 * mongodb v1.0
 * create by dongbo
 * 待扩展
 */
namespace Think;

class Mongodb{

    private static $obj;

    private static $mongo;
    
    private static $database;
    
    private static $collection;
    
    public static function create($str = "default"){
        if(!self::$obj instanceof \Mongodb){
            self::$obj = new self($str);
        }
        return self::$obj;
    }
    
    private function __construct($str) {
        $argv = "mongodb://";
        if (C("MONGO_USER") != "" && C("MONGO_PWD") != ""){
                $argv .= C("MONGO_USER").":".C("MONGO_PWD")."@";
        }
        $host = C("MONGO_HOST")==""?"127.0.0.1":C("MONGO_HOST");
        if(C("MONGO_PORT") == ""){
            $argv .= $host;
        }else{
            $argv .= "$host:".C("MONGO_PORT");
        }
        self::$mongo = new \Mongo($argv);
    }
    
    public function selectDatabase($database){
        self::$database = self::$mongo->selectDB($database);
    }
    
    public function selectCollection($collection){
        if(!self::$database){
            return false;
        }
        self::$collection = self::$database->$collection;
    }
    
    public function insert($data){
        if(!self::$collection){
            return false;
        }
        return self::$collection->insert($data);
    }
    
    public function update($where,$data){
        if(!self::$collection){
            return false;
        }
        return self::$collection->update($where,$data);
    }
    
    public function findOne($where){
        if(!self::$collection){
            return false;
        }
        $re = self::$collection->find($where);
        foreach ($re as $v) {
            return $v;
        }
    }
    
    public function findAll($where=0){
        if(!self::$collection){
            return false;
        }
        if($where==0){
            $re = self::$collection->find();
        }else{
            $re = self::$collection->find($where);
        }
        $_re = array();
        foreach ($re as $v) {
            $_re[]=$v;
        }
        return $_re;
    }
    
}
